<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/23
 * Time: 17:38
 *后台 活动管理控制器
 */

namespace app\portal\controller;

use cmf\controller\AdminBaseController;
use app\portal\model\ActivityModel;
use app\portal\model\OrganizeModel;
use think\Db;
use cmf\phpqrcode\QRcode;
use think\facade\Env;


class AdminActivityController extends AdminBaseController
{

    public function server_content(){
        $data=Db::name('server_content')->select();
        $this->assign('data',$data);
        return $this->fetch();
    }
    //添加/修改服务内容
    public function server_content_add(){
        $id=input('id');
        if($id){
            $data=Db::name('server_content')->find($id);
            $this->assign('data',$data);
        }
        $this->assign('id',$id);
        return $this->fetch();
    }
    //保存添加/修改服务内容
    public function save_server_content(){
        $data=input('post.');
        if(empty($data['id'])){
            unset($data['id']);
            $result = Db::name('server_content')->insert($data);
            if ($result === false) {
                $this->error('添加失败!');
            }
            $this->success('添加成功!', url('AdminActivity/server_content'));
        }else{
            $result = Db::name('server_content')->update($data);
            if ($result === false) {
                $this->error('修改失败!');
            }
            $this->success('修改成功!', url('AdminActivity/server_content'));
        }
    }
    public function activity_type(){
        $data=Db::name('activity_type')->select();
        $this->assign('data',$data);
        return $this->fetch();
    }
    //添加/修改活动类型
    public function activity_type_add(){
        $id=input('id');
        if($id){
            $data=Db::name('activity_type')->find($id);
            $this->assign('data',$data);
        }
        $this->assign('id',$id);
        return $this->fetch();
    }
    //保存添加/修改活动类型
    public function save_activity_type(){
        $data=input('post.');
        if(empty($data['id'])){
            unset($data['id']);
            $result =Db::name('activity_type')->insert($data);
            if ($result === false) {
                $this->error('添加失败!');
            }
            $this->success('添加成功!', url('AdminActivity/activity_type'));
        }else{
            $result = Db::name('activity_type')->update($data);
            if ($result === false) {
                $this->error('修改失败!');
            }
            $this->success('修改成功!', url('AdminActivity/activity_type'));
        }
    }
    public function index(){
        $where=[];
        $assign=[];
        $param = $this->request->param();
        if(!empty($param['keyword'])){
            $where[]=['title','like','%'.$param['keyword'].'%'];
            $assign['keyword']=$param['keyword'];
        }
        if(!empty($param['start_time'])&&!empty($param['end_time'])){
            $start_time=strtotime($param['start_time']);
            $end_time=strtotime($param['end_time']);
            $where[]=['ctime','between',[$start_time,$end_time]];
            $assign['start_time']=$param['start_time'];
            $assign['end_time']=$param['end_time'];
        }
        //dump($where);
        $db=new ActivityModel();
        $data=$db->with('user')->with('log')->where($where)->order('ctime desc')->paginate(15);
        foreach ($data as $k=>$v){
            $data[$k]['place']=json_decode($v['place']);
            $data[$k]['time']=json_decode($v['time']);
        }
        $assign['data']=$data;
        $this->assign('page',$data->render());
        $this->assign($assign);
        return $this->fetch();
    }

    function fix_qr(){
        $result = [];
        $id =input("id/d",0);
        $db=new ActivityModel();
        try{
            if(!$id){
                throw new \Exception("ID 缺失");
            }
            $base_url  = request()->domain();
            $url=$base_url.'/mobile/activity/details?id='.$id;
            $qrcode=$this->qrcode($url);
            $op_result = $db->where('id',$id)->update(['qrcode'=>$qrcode]);
            if($op_result===false){
                throw new \Exception("更新失败，请联系管理人员.");
            }

            $result["error"] = false;
            $result["errmsg"] = "二维码更新成功~";
            $result["data"] =  request()->domain().'/upload/qrcode/'.$qrcode.'.png';
        }catch(\Exception $e){
            $result["error"] = true;
            $result["errmsg"] = $e->getMessage();
        }
        return json($result);
    }

    //添加活动页面
    public function add(){
        $Model = new ActivityModel();
        $id=input('id');
        $server_content=Db::name('server_content')->select();
        $activity_type=Db::name('activity_type')->select();
        $big_team = Db::name('organize')->field('id,name')->select();
        if($id){
            $data=$Model->find($id);
            $this->assign('data',$data);
            $this->assign('id',$id);
        }
        $this->assign('server_content',$server_content);
        $this->assign('big_team',$big_team);
        $this->assign('activity_type',$activity_type);
        return $this->fetch();
    }
    //添加活动页面1.0
//    public function adds(){
//        $Model = new ActivityModel();
//        $id=input('id');
//        $org_id=input('org_id');
//        $org=Db::name('organize')->where('id',$org_id)->value('name');
//        $this->assign('condition',false);
//        if($id){
//            $data=$Model->find($id);
//            $data['place']=json_decode($data['place']);
//            $data['point']=json_decode($data['point']);
//            $data['time']=json_decode($data['time']);
//            $this->assign('data',$data);
//           if(!input('copy')){
//               $this->assign('id',$id);
//               if(time()>$data['end_date']+60*40*24){
//                   $this->assign('condition',true);
//               }
//           }else{
//               $this->assign('copy',true);
//           }
//        }
//        $this->assign('org_id',$org_id);
//        $this->assign('org',$org);
//        return $this->fetch();
//    }

    /**保存活动页面2.0*/
    public function addPost(){
        $db=new ActivityModel();
        $data=input('post.');
        $result = $this->validate($data, 'AdminActivity');
        if ($result !== true) {
            $this->error($result);
        }
        $data['ctime']=time();
        $data['admin']=session('ADMIN_ID');
        $data['start_time']=strtotime($data['start_time']);
        $data['end_time']=strtotime($data['end_time']);
        unset($data['big_team']);
        unset($data['mid_team']);
        unset($data['query']);
       // dump($data);exit;

        if(empty($data['id'])){
            unset($data['id']);
            $result = $db->insertGetId($data);
            if ($result === false) {
                $this->error('添加失败!');
            }
            $base_url  = request()->domain();
            $url=$base_url.'/mobile/activity/details?id='.$result;
            $qrcode=$this->qrcode($url);
            $result = $db->where('id',$result)->update(['qrcode'=>$qrcode]);
            if ($result === false) {
                $this->error('添加二维码失败!');
            }
            $this->success('添加成功!', url('AdminActivity/index'));
        }else{
            $result = $db->update($data);
            if ($result === false) {
                $this->error('修改失败!');
            }
            $this->success('修改成功!', url('AdminActivity/index'));
        }
    }
    //删除活动
    public function activity_del(){
        $Model = new ActivityModel();
        $id= $this->request->param('id');
        $result=$Model->where('id',$id)->delete();
        if ($result) {
            $this->success('删除成功!');
        } else {
            $this->error('删除失败');
        }
    }

    //生成二维码
    public function qrcode($url){
        $errorCorrectionLevel = 'L';
        $matrixPointSize = 5;
        $folder_path = Env::get('root_path').'public'.DIRECTORY_SEPARATOR.'upload'.DIRECTORY_SEPARATOR.'qrcode'.DIRECTORY_SEPARATOR;
        $uuid = uniqid();
        $filename = $folder_path.$uuid.'.png';
        if(!is_dir($folder_path)){
            mkdir($folder_path,0777,true);
        }
        try{
            QRcode::png($url,$filename , $errorCorrectionLevel, $matrixPointSize, 2);
        }catch(\Exception $e){
            return false;
        }
        
        return $uuid;
    }

}